<template>
	<div class="maskBox reportFormBox">
		<div class="maskContentBox bg-white rela padding-trbl-20">
			<div class="maskContent bg-white">
				<div class="reportFormTitle font-24 text-center">
					{{exportFormData.year}}年{{exportFormData.month}}月份芳草街街道办事处</br>网络理政工作分析报告
				</div>
				<div class="margin-t-10">
					<div class="formItemTitle text-index2 font-18">一、总体情况</div>
					<div class="text-index2">
						{{exportFormData.fromDate}}至{{exportFormData.toDate}}政务服务办公室共签收转办网络理政工单{{exportFormData.total}}件，市委书记信箱{{exportFormData.totalShuji}}件，
						市长信箱{{exportFormData.totalShizhang}}件。相比{{exportFormData.lastMonthYear}}年{{exportFormData.lastMonth}}月份，本月网络理政平台诉求总量略有{{exportFormData.add?'上升':'下降'}}，
						数量{{exportFormData.add?'增加':'减少'}}{{exportFormData.addCount}}件，环比{{exportFormData.add?'上升':'下降'}}{{exportFormData.huanbi}}%。
						<div class="ybEchart1 width100 margin-t-10" id="ybEchart1" ref="ybEchart1"></div>
						<div class="font-14 text-center">
							{{exportFormData.year}}年网络理政总体情况
						</div>
						<div class="text-index2 margin-t-10">
							本月工单平均回复周期{{exportFormData.hfzq}}个工作日，环比{{exportFormData.hfzqAdd?'上升':'下降'}}{{exportFormData.hfzqHuanbi}}个工作日；
							环比转办量{{exportFormData.hfzqZhuanbanAdd?'增加':'减少'}}{{exportFormData.hfzqZhuanban}}件。
						</div>
					</div>
					<div class="margin-t-10">
						<div class="formItemTitle text-index2 font-18">（一）按办理内容分类</div>
						<div class="text-index2 margin-tb-10">
							<span v-for="(item,index) in nr_Workorder" :key="index">
								{{item.category}}{{item.count}}件<template v-if="index<nr_Workorder.length-1">、</template>
							</span>。各类型情况见图。（{{categoryTotal}}件）
						</div>
						<div class="ybEchart2 width100" id="ybEchart2" ref="ybEchart2"></div>
					</div>
					<div class="">
						<div class="formItemTitle font-18">（二）按办理部门（社区）分类</div>
						<div class="formItemTitle font-18 text-index2 margin-tb-10">1.满意率排名前三位部门</div>
						<div class="text-index2">
							{{exportFormData.bumen3}}。
						</div>
						<formTable tableTitle="各部门本月办件情况表" tableType="yb" :tableData="bmFormTableData"></formTable>
						<div class="formItemTitle font-18 text-index2 margin-tb-10">2.满意率排名前三位社区</div>
						<div class="text-index2">
							{{exportFormData.shequ3}}。
						</div>
						<formTable tableTitle="各社区本月办件情况表" tableType="yb" :tableData="sqFormTableData"></formTable>
					</div>
				</div>
				<div class="margin-t-10">
					<div class="font-18 reportFormTitle">
						二、热点问题及办理情况
					</div>
					<div class="zbHotBox margin-t-10">
						<div class="hotEchart margin-b-20 bg-white" ref="imageWrapper">
							<div class="flex-row row-center zbHotItem width100 padding-b-4">
								<div class="zbHotItemClom1 margin-r-10">承办部门</div>
								<div class="zbHotItemClom2" style="opacity: 0;">事件</div>
								<div class="zbHotItemClom3 text-center">总量</br>（件）</div>
								<!-- <div class="zbHotItemClom4">增减量</br>（件）</div> -->
							</div>
							<div class="flex-row row-center zbHotItem width100 padding-tb-4" :class="index<hotTabData.length?'margin-b-10':''" v-for="(item,index) in hotTabData" :key="index">
								<div class="zbHotItemClom1 margin-r-10">{{item.caseDept}}</div>
								<div class="zbHotItemClom2">
									<div class="zbHotClomTitle flex-row rdInfo">
										<!-- <div class="title text-cut margin-r-5">[{{item.ldlb}}]{{item.nrlb}}</div> -->
										<!-- <div class="time padding-l-5" v-if="item.continuedMonthCount>1">连续{{item.continuedMonthCount}}个月热点</div> -->
										<!-- <div class="time padding-l-5" v-else>本月新增热点</div> -->
									</div>
									<div class="zbHotProgress">
										<div class="circleProgress bg-light-blue" :style="{width:item.progress+'%'}"></div>
									</div>
								</div>
								<div class="zbHotItemClom3 text-center">{{item.count}}</div>
								<!-- <div class="zbHotItemClom4" :class="item.add?'text-light-red':'text-green'"><i :class="item.add?'el-icon-top':'el-icon-bottom'"></i> {{item.addCount}}</div> -->
							</div>
						</div>
						<div class="text-index2 margin-b-5">
							详细如下：
						</div>
						<el-table
							:data="hotTabData"
							border
							style="width: 100%">
							<el-table-column
								label="序号"
								type="index"
								width="40"
								align="center">
							</el-table-column>
							<el-table-column
								prop="caseContent"
								label="主要问题">
							</el-table-column>
							<el-table-column
								label="月件数"
								prop="count"
								width="40"
								align="center">
							</el-table-column>
							<el-table-column
								label="办理部门(社区)"
								prop="caseDept"
								width="70"
								align="center">
							</el-table-column>
							<el-table-column
								label="包案领导"
								prop="caseLeader"
								width="70"
								align="center">
							</el-table-column>
							<el-table-column
								prop="caseReply"
								label="处理情况">
							</el-table-column>
						</el-table>
						<div class="text-right margin-t-20 margin-r-20">
							政务服务办公室</br>{{dateTime}}
						</div>
					</div>
				</div>
			</div>
			<div class="buttonBox width100 abso text-right">
				<div class="cancel line-block margin-r-20 exportBtn pointer padding-lr-20" @click="reportFormHide">取消</div>
				<div class="line-block exportBtn pointer bg-violet text-white padding-lr-20 margin-r-20" @click="renderDoc">导出</div>
			</div>
		</div>
	</div>
</template>
<script type="text/javascript">
	import formTable from './myTable1.vue'
	import * as echarts from 'echarts'
	import html2canvas from 'html2canvas'
	import Docxtemplater from "docxtemplater";
	import PizZip from "pizzip";
	import PizZipUtils from "pizzip/utils/index.js";
	import {saveAs} from "file-saver";
	import ImageModule from "docxtemplater-image-module-free"
	// 读取并获得模板文件的二进制内容
	function loadFile(url, callback) {
		PizZipUtils.getBinaryContent(url, callback);
	}
	export default {
		props:{
			exportFormData:{
				type: Object,
				default: []
			},
			dateTime:{
				type: String,
				default: ''
			}
		},
		components: {
			formTable
		},
		data() {
			return {
				echart1BaseUrl: '',
				echart2BaseUrl: '',
				hotImgUrl: '',
				nr_Workorder: [],
				categoryTotal: 0,
				hotTabData: [],
				bmFormTableData: [],
				sqFormTableData: [],
				blnrList: ''
			}
		},
		mounted() {
			this.nr_Workorder = this.exportFormData.categories
			this.nr_Workorder.forEach((item,index)=>{
				if(index<this.nr_Workorder.length-1){
					this.blnrList += item.category+item.count+'件、'
				}else{
					this.blnrList += item.category+item.count+'件。'
				}
				this.categoryTotal += item.count
			})
			this.exportFormData.redians.forEach((item,index)=>{
				item.index = index+1
				if(item.caseReply){
					item.caseReply = item.caseReply.replace(/\n;/g, "").trim().replace(/^(null;[\r\n\s]*)?来([电信话]\/)?[电信话]人：[\r\n\s]*(您好！)?[\r\n\s]*/, "").trim().replace(/\d{4}年\d{1,2}月\d{1,2}日$/, "").trim().replace(/(高新区)?(芳草街街道办事处|芳草街街道)?(社区发展办|市场监督管理所|执法中队|蓓蕾社区|劳就办|盛泰社区|民生服务办|神仙树社区|紫荆社区|紫薇社区|紫竹社区|综合办|城市管理办|退役军人服务站|卫生服务中心|社区治理办|政务服务办|民政服务办|党群办|营商环境建设办|芳华社区|雅乐隔离酒店|沙子堰社区|新能社区|芳草街街道|芳草街街道社区发展办公室|芳草街街道市场监督管理所|芳草街街道城市管理综合执法中队|芳草街街道蓓蕾社区|芳草街街道劳动就业和社会保障服务办公室|芳草街街道盛泰社区（筹备组）|芳草街街道民生服务办公室|芳草街街道神仙树社区|芳草街街道紫荆社区|芳草街街道紫薇社区|芳草街街道紫竹社区|芳草街街道综合办公室|芳草街街道城市管理办公室|芳草街街道退役军人服务站|芳草街街道社区卫生服务中心|芳草街街道社区治理办公室|芳草街街道政务服务办公室|芳草街街道民政服务办公室|芳草街街道党群办公室|芳草街街道营商环境建设办公室|芳草街街道芳华社区|芳草街街道雅乐隔离酒店工作组|芳草街街道沙子堰社区|芳草街街道新能社区)?$/, "").trim()
				}
				item.progress = item.count/this.exportFormData.redianMax*100
				this.hotTabData.push(item)
			})
			this.exportFormData.bumens.forEach((item,index)=>{
				item.index = index+1
				if(item.hf==0){
					item.hf = '--'
				}
				if(item.hfzq==0){
					item.hfzq = '--'
				}
				if(item.cq==0){
					item.cq = '--'
				}
				if(item.myl>0){
					item.myl = item.myl+'%'
				}else{
					item.myl = '--'
					item.rank = '--'
				}
				this.bmFormTableData.push(item)
			})
			this.exportFormData.shequs.forEach((item,index)=>{
				item.index = index+1
				if(item.hf==0){
					item.hf = '--'
				}
				if(item.hfzq==0){
					item.hfzq = '--'
				}
				if(item.cq==0){
					item.cq = '--'
				}
				if(item.myl>0){
					item.myl = item.myl+'%'
				}else{
					item.myl = '--'
					item.rank = '--'
				}
				this.sqFormTableData.push(item)
			})
			this.ndEchart()
			this.nrWorkorder()
		},
		methods:{
			// 年度统计
			ndEchart(){
				const that = this
				const ybEchart1 = document.getElementById('ybEchart1')
				const yb_demo1 = echarts.init(ybEchart1)
				let data1 = [],
						data2 = []
				that.exportFormData.monthGls.forEach(item=>{
					data1.push(item.month)
					data2.push(item.count)
				})
				const option = {
					color: ['#8565ff'],
					grid: {
						left: '10px',
						right: '10px',
						bottom: '10px',
						top: '20px',
						containLabel: true
					},
				  xAxis: {
				    type: 'category',
				    data: data1
				  },
				  yAxis: {
				    type: 'value',
						max: function(value){
							if(value.max==0){
								return 5
							}
						}
				  },
				  series: [
				    {
				      data: data2,
				      type: 'bar',
							label: {
								show: true,
								position: 'top',
								formatter: function (params) {
									if(params.data>0){
										return params.data
									}else{
										return ''
									}
								},
								color: '#8565ff',
							}
				    }
				  ]
				}
				ybEchart1 && yb_demo1.setOption(option)
				setTimeout(function(){
					that.getBaseImage(yb_demo1, 'ybEchart1')
				},2000)
			},
			// 诉求内容分类统计表
			nrWorkorder() {
				const that = this
				const ybEchart2 = document.getElementById('ybEchart2')
				const yb_demo2 = echarts.init(ybEchart2)
				let data1 = [],
						data2 = []
				that.nr_Workorder.forEach(item=>{
					data1.push(item.category)
					data2.push(item.count)
				})
				const option = {
						tooltip: {
							trigger: 'axis',
							show: false,
							axisPointer: { // 坐标轴指示器，坐标轴触发有效
								type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
							},
						},
						legend: {
							show:false
						},
						grid: {
							top: '2%',
							left: '3%',
							right: '10%',
							bottom: 0,
							containLabel: true
						},
						xAxis: [{
							splitLine: {
								show: false
							},
							type: 'value',
							show: false,
						}],
						yAxis: [{
							splitLine: {
								show: false
							},
							axisLine: { //y轴
								show: false
							},
							type: 'category',
							axisTick: {
								show: false
							},
							inverse: true,
							data: data1,
							axisLabel: {
								color: '#000',
								fontSize: 14,
							}
						}],
						series: [{
							name: '标准化',
							type: 'bar',
							barWidth: 12, // 柱子宽度
							label: {
								show: true,
								position: 'right', // 位置
								color: '#000',
								fontSize: 14,
								distance: 15, // 距离
								formatter: '{c} 件' // 这里是数据展示的时候显示的数据
								}, // 柱子上方的数值
								itemStyle: {
									barBorderRadius: [0, 20, 20, 0], // 圆角（左上、右上、右下、左下）
									color: '#8565ff'
								},
								data: data2
						}, ]
				};
				ybEchart2 && yb_demo2.setOption(option)
				setTimeout(function(){
					that.getBaseImage(yb_demo2, 'ybEchart2')
				},2000)
			},
			// 获取echart图表的图片
			getBaseImage(chart, chartId) {
				let url = chart.getDataURL({
					pixeRatio: 2,
					background: '#ffffff'
				})
				if(chartId === 'ybEchart1'){
					this.echart1BaseUrl = url
				}else{
					this.echart2BaseUrl = url
				}
				this.hotImg()
			},
			base64DataURLToArrayBuffer(dataURL) {
			  const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
			  if (!base64Regex.test(dataURL)) {
			    return false;
			  }
			  const stringBase64 = dataURL.replace(base64Regex, "");
			  let binaryString;
			  if (typeof window !== "undefined") {
			    binaryString = window.atob(stringBase64);
			  } else {
			    binaryString = new Buffer(stringBase64, "base64").toString("binary");
			  }
			  const len = binaryString.length;
			  const bytes = new Uint8Array(len);
			  for (let i = 0; i < len; i++) {
			    const ascii = binaryString.charCodeAt(i);
			    bytes[i] = ascii;
			  }
			  return bytes.buffer;
			},
			// 热点事件统计图
			hotImg() {
				html2canvas(
					this.$refs.imageWrapper,{
						backgroundColor: null     // 解决生成的图片有白边
					},
				)
				.then((canvas) => {
					let dataURL = canvas.toDataURL("image/jpg")
					this.hotImgUrl = dataURL
				})
			},
			// 导出文档
			renderDoc() {
				const that = this
				// demo.docx是模板。我们在导出的时候，会根据此模板来导出对应的数据
				loadFile("monthlyReport.docx", function(
					error,
					content
				) {
					// 抛出异常
					if (error) {
						throw error;
					}
			
					// 创建一个JSZip实例，内容为模板的内容
					const zip = new PizZip(content);
					// 创建并加载docxtemplater实例对象
					let doc = new Docxtemplater().loadZip(zip);
					
					// 图片处理
					const opts = {
						centered: true,
						fileType: "docx",
						getImage: function (img, tagValue) {
							return that.base64DataURLToArrayBuffer(img);
						},
						getSize: function(img, tagValue, tagName){
							if(tagName === 'ndImg'){
								return [that.$refs.ybEchart1.offsetWidth, that.$refs.ybEchart1.offsetHeight]
							}
							if(tagName === 'sqnrImg'){
								return [that.$refs.ybEchart2.offsetWidth, that.$refs.ybEchart2.offsetHeight]
							}else{
								return [that.$refs.imageWrapper.offsetWidth, that.$refs.imageWrapper.offsetHeight]
							}
						}
					}
					let countState = '',
							hfzqHb = ''
					if(that.exportFormData.add){
						countState += '本月网络理政平台诉求总量略有上升，数量增加'+that.exportFormData.addCount+'件，环比上升'+that.exportFormData.huanbi+'%'
					}else{
						countState += '本月网络理政平台诉求总量略有下降，数量减少'+that.exportFormData.addCount+'件，环比下降'+that.exportFormData.huanbi+'%'
					}
					if(that.exportFormData.hfzqAdd){
						hfzqHb = '环比上升'+that.exportFormData.hfzqHuanbi+'个工作日；'
					}else{
						hfzqHb = '环比下降'+that.exportFormData.hfzqHuanbi+'个工作日；'
					}
					if(that.exportFormData.hfzqZhuanbanAdd){
						hfzqHb += '环比转办量增加'+that.exportFormData.hfzqZhuanban+'件'
					}else{
						hfzqHb += '环比转办量减少'+that.exportFormData.hfzqZhuanban+'件'
					}
					let imageModule = new ImageModule(opts);
					doc.attachModule(imageModule);
					doc.setData({
						ndImg: that.echart1BaseUrl,
						sqnrImg: that.echart2BaseUrl,
						hotImg: that.hotImgUrl,
						hotList: that.hotTabData,
						bumen3: that.exportFormData.bumen3,
						shequ3: that.exportFormData.shequ3,
						fromDate: that.exportFormData.fromDate,
						countState: countState,
						hfzq: that.exportFormData.hfzq,
						hfzqHb: hfzqHb,
						lastMonth: 11,
						lastMonthYear: 2021,
						month: that.exportFormData.month,
						toDate: that.exportFormData.toDate,
						total: that.exportFormData.total,
						totalShizhang: that.exportFormData.totalShizhang,
						totalShuji: that.exportFormData.totalShuji,
						year: that.exportFormData.year,
						blnrList: that.blnrList,
						blnrTotal: that.categoryTotal,
						bm: that.bmFormTableData,
						sq: that.sqFormTableData,
						dateTime: that.dateTime
					});
					try {
						// 用模板变量的值替换所有模板变量
						doc.render();
					} catch (error) {
						// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
						function replaceErrors(key, value) {
							if (value instanceof Error) {
								return Object.getOwnPropertyNames(value).reduce(function(
									error,
									key
								) {
									error[key] = value[key];
									return error;
								}, {});
							}
							return value;
						}
						console.log(JSON.stringify({
							error: error
						}, replaceErrors));
			
						if (error.properties && error.properties.errors instanceof Array) {
							const errorMessages = error.properties.errors
								.map(function(error) {
									return error.properties.explanation;
								})
								.join("\n");
							console.log("errorMessages", errorMessages);
							// errorMessages is a humanly readable message looking like this : 'The tag beginning with "foobar" is unopened'
						}
						throw error;
					}
					// 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
					const out = doc.getZip().generate({
						type: "blob",
						mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
					});
					// 将目标文件对象保存为目标类型的文件，并命名
					const title = that.exportFormData.year+'年'+that.exportFormData.month+'月份芳草街街道办事处网络理政工作分析报告.docx'
					saveAs(out, title);
				});
			},
			reportFormHide(){
				this.$emit('reportFormHide', false)
			}
		}
	}
</script>
<style lang="less" scoped>
	.reportFormBox{
		.maskContentBox{
			width: 640px;
			height: 889px;
			.maskContent{
				height: 800px;
				overflow-y: scroll;
				padding-bottom: 0;
				.reportFormTitle{
					font-weight: 560;
				}
				.formItemTitle{
					font-weight: 560;
				}
				.ybEchart1{
					height: 300px;
				}
				.ybEchart2{
					height: 350px;
				}
				.zbHotBox{
					.hotEchart{
						.zbHotItem{
							background: rgba(238, 238, 238, .4);
							.zbHotItemClom1{
								width: 100px;
							}
							.zbHotItemClom3{
								width: 50px;
							}
							.zbHotItemClom4{
								width: 80px;
							}
							.zbHotItemClom2{
								width: calc(100% - 150px);
								.rdInfo{
									height: 30px;
								}
								.zbHotClomTitle{
									.title{
										width: 180px;
									}
									.time{
										border-left: 5px solid #8565ff;
									}
								}
								.zbHotProgress{
									width: 100%;
									height: 15px;
									.circleProgress{
										height: 100%;
									}
								}
							}
						}
						.zbHotItem:first-child{
							background: none;
							border-bottom: 1px solid #333;
						}
					}
				}
			}
			.buttonBox{
				right: 0;
				bottom: 10px;
				.cancel{
					border: 1px solid #ccc;
				}
			}
		}
	}
</style>
<style lang="less" type="text/css">
	.reportFormBox{
		.el-table--border, .el-table--group{
			border-color: #000000;
		}
		.el-table, .el-table thead{
			color: #000;
		}
		.el-table thead{
			.el-table__cell{
				text-align: center;
			}
		}
		.el-table--border::after, .el-table--group::after, .el-table::before{
			background-color: #000000;
		}
		.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
			border-bottom: 1px solid #000000;
		}
		.el-table--border .el-table__cell, .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed{
			border-right: 1px solid #000000;
		}
	}
</style>